#!/bin/bash
# author:lixiang
# 把指定目录下的所有音频文件，随机,均分添加5dB,10dB,15dB的背景噪音并记录

# 判断传入的参数
if [ ! -n "$1" ]
then
    echo "缺少数据源参数"
    echo "usage: sh add_noise.sh orig orig_ac2 noise.wav"
    exit 1
fi

if [ ! -n "$2" ]
then
    echo "缺少输出目录参数"
    echo "usage: sh add_noise.sh orig orig_ac2 noise.wav"
    exit 1
fi

if [ ! -n "$3" ]
then
    echo "缺少噪音文件参数"
    echo "usage: sh add_noise.sh orig orig_ac2 noise.wav"
    exit 1
fi

# 噪音模块安装路径
cd /data2/tool/addnoise

WORKDIR=$1

# 清除
rm -rf temp.txt wav_in.txt

find ${WORKDIR} -type f -iname '*.wav' > temp.txt
# 随机打乱行
shuf temp.txt -o wav_in.txt

array=(5 10 15)
# 文件总数
fileCount=`cat temp.txt | wc -l`
# 平均值
averageCount=`expr $fileCount / ${#array[*]}`
# 截取行数
str="1,${averageCount}d"

for snr in ${array[*]}
do
  filename=`basename $1`
  wav_in_file=wav_in_${snr}dB.txt
  wav_out_file=wav_out_${snr}dB.txt

  # 判断是否是最后一个，如果不是，按平均值分配，如果是，则剩余部分分给最后要执行的
  if [ $snr != ${array[*]: -1} ]
  then
    # 生成wav_in_${snr}dB.txt
    head  -n $averageCount wav_in.txt > $wav_in_file
    sed 's/\.wav/.noisy.wav/g' $wav_in_file > $wav_out_file
    # 删除已执行过的行
    sed -i $str wav_in.txt
  else
    cat wav_in.txt > $wav_in_file
    sed 's/\.wav/.noisy.wav/g' $wav_in_file > $wav_out_file
  fi

  echo Adding ${snr} dB noise...
  echo ""
  # 执行添加噪音脚本
  ./addnoise.sh -n $3 -s $snr -d -1 $wav_in_file $wav_out_file
  for user in $(ls ${WORKDIR})
  do
    mkdir -p $2/$filename/$user
    #查询数据源目录下所有带噪音的音频文件，然后复制到输出目录
    find ${WORKDIR}/$user -name "*.noisy.wav" -exec cp -r {} $2/$filename/$user \;
    # 输出目录下的音频文件重命名
    rename .noisy. . $2/$filename/$user/*
    # 把记录文件移动到相应的目录下
    mv -f $wav_in_file $2/$filename
  done
  # 删除数据源目录下所有带噪音的音频文件
  find ${WORKDIR} -name '*.raw' -delete
  find ${WORKDIR} -name '*.noisy.wav' -delete
done
